<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions" class="is--card">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.input.type" style="width: 100px">
            <el-option label="采购单号" value="purchase_no"></el-option>
            <el-option label="来源单号" value="inbound_no"></el-option>
          </el-select>
          <el-input v-model="form.input.value" placeholder="请输入" class="w-40"></el-input>
        </VGroup>
        <VGroup>
          <el-select v-model="form.skuInfo.type" class="w-28">
            <el-option label="sku" value="sku"></el-option>
            <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            <el-option label="自定义sku" value="custom_sku"></el-option>
          </el-select>
          <el-input v-model="form.skuInfo.value" placeholder="请输入" class="w-40"></el-input>
        </VGroup>
        <VSelect v-model="form.supplier_name" placeholder="供应商" type="supplierName" allow-create style="min-width: 200px" multiple collapse-tags clearable filterable />
        <VSelect v-model="form.order_source" placeholder="订单来源" :options="options.order_source" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.destination_warehouse" placeholder="目的仓库" type="warehouse156" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.purchase_type" placeholder="供应商类型" :options="options.purchase_type" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.period_id" placeholder="结算方式" type="period" multiple collapse-tags style="min-width: 220px" />
        <VSelect v-model="form.purchase_type" placeholder="供应商类型" :options="options.purchase_type" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.company_id" placeholder="公司主体" :options="options.company_id" multiple collapse-tags style="min-width: 210px" />
        <VSelect v-model="form.purchase_status" placeholder="采购状态" :options="options.purchase_status" multiple collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.purchase_user_id" placeholder="采购人员" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.finance_status" placeholder="财务状态" :options="options.finance_status" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.is_billing" placeholder="是否已开票" :options="options.is_billing" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.inbound_type" placeholder="入库类型" :options="options.inbound_type" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.is_label" placeholder="是否不开票" :options="options.is_label" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <div class="v-group-item">入库时间</div>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <el-tabs v-model="type" class="w-full" @tab-click="typeChange">
          <el-tab-pane label="全部" name="0"></el-tab-pane>
          <el-tab-pane label="深圳主体" name="1"></el-tab-pane>
          <el-tab-pane label="香港主体" name="2"></el-tab-pane>
        </el-tabs>
        <template v-if="!view">
          <VButton auth="/purchase/finance/verification/inbound/billing" type="primary" @click="handleBatch('billing')"><svg-icon icon-class="sc" class="mr-1"
              style="font-size: 15px" />生成开票清单</VButton>
          <VButton auth="/purchase/finance/verification/inbound/updateIsBilling" @click="handleBatch('updateIsBilling')">无需生成开票清单</VButton>
          <VButton auth="/purchase/finance/verification/inbound/adjust" @click="handleBatch('adjust')">调整</VButton>
          <VTotal :data="total"
            :options="[{ title: '入库数量', key: 'inbound_num' }, { title: '含税入库金额', key: 'inbound_price_tax' }, { title: '含税折扣', key: 'preferential_price_tax' }, { title: '含税售后', key: 'after_sale_price_tax' }]"
            class="ml-auto" />
          <VExport auth="/purchase/finance/verification/inbound/export" mainKey="pi_id" name="purchase-inbound" :tableRef="tableRef" task />
        </template>
        <VExport v-else auth="/purchase/manage/inbound/export" mainKey="pi_id" name="purchase-inbound" :tableRef="tableRef" task />
      </template>
    </VTable>
    <VLog ref="logRef" />
    <Adjust ref="adjustRef" @success="query" />
  </VPage>
</template>
  
<script setup lang="jsx">
import api from './api'
import VTotal from '@/components/VTotal'
import Adjust from './components/Adjust'
import { getOption } from '@/api/public'
import { resMessage, resSkip } from '@/utils/res'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  view: Boolean,
})

const baseName = 'purchase_inbound'
const tableRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

const type = ref('0')
const typeChange = val => {
  tableRef?.value.setFormField('company_type', val.paneName)
  query()
}

// 批量操作
const adjustRef = ref()
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  const pi_ids = selection.map(d => d.pi_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const billing = (params) => {
    showLoading()
    api.billing({...tableRef.value.getQueryForm(), pi_ids, ...params}).then(res => {
      resSkip({
        res,
        closeLoading,
        showMessage: false,
        props: {
          showCancelButton: true,
          cancelButtonText: '取消',
          confirmButtonText: '跳过继续生成',
        },
        success: () => {
          resMessage({
            res,
            success: () => {
              ElMessage.success('操作成功')
              query()
            }
          })
        },
        submit: () => {
          billing(res.data)
        },
      })
    }).finally(closeLoading)
  }
  if (!selection.length && !['billing', 'adjust'].includes(name)) {
    ElMessage.warning('请先选择行')
    return
  }
  const handle = {
    billing: () => {
      billing({is_skip: 1})
    },
    adjust: () => {
      adjustRef?.value.open({...tableRef.value.getQueryForm(), pi_ids})
    },
    updateIsBilling: () => {
      showLoading()
      api.updateIsBilling({ pi_ids }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    },
  }
  handle[name]()
}

// 单行操作
const logRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { pi_id } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    log: () => {
      logRef?.value.open({ log_type: baseName, pi_id })
    },
  }
  handle[name]()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  getOption({ type: 'purchase' }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] }),
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 列表配置
const total = ref([])
const tableOptions = reactive({
  showHeaderOverflow: false,
  rowConfig: {height: 72},
  formConfig: {
    data: {
      company_type: '0',
      input: { type: 'purchase_no', value: '' },
      skuInfo: { type: 'sku', value: '' },
      dateRange: { type: 'inbound_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: 40, fixed: 'left' },
    { title: '入库时间', field: 'inbound_time', minWidth: 180, },
    { title: '入库类型', field: 'inbound_type_name', minWidth: 100, },
    { title: '入库仓', field: 'destination_warehouse_name', minWidth: 120, },
    { title: '供应商', field: 'supplier_name', minWidth: 140, slots: {
      default: ({row}) => <VText value={row.supplier_name} line={2} />
    } },
    {
      minWidth: 220, slots: {
        header: () => <div>采购信息</div>,
        default: ({ row }) => <div>
          <VText title='结算方式' value={row.period_name} line={1}></VText>
          <VText title='支付方式'>{row.payment_type_name}</VText>
        </div>
      }
    },
    { title: '部门', field: 'department_name', minWidth: 120, slots: {
      default: ({row}) => <VText value={row.department_name} line={2} />
    } },
    { title: '公司主体', field: 'company_id_name', minWidth: 120, slots: {
      default: ({row}) => <VText value={row.company_id_name} line={2} />
    } },
    { title: '采购单号', field: 'purchase_no', minWidth: 160, },
    { title: '采购人员', field: 'purchase_user', minWidth: 100, },
    { title: 'SKU', field: 'sku', minWidth: 180, },
    { title: '下单数量', field: 'sku_purchase_num', minWidth: 100, },
    {
      minWidth: 150, slots: {
        header: () => <div>开票品名<br />报关品名</div>,
        default: ({ row }) => <div>
          <VText title='开票'>{row.invoice_name}</VText>
          <VText title='报关'>{row.declare_name}</VText>
        </div>
      }
    },
    { title: '报关数量', field: 'declare_num', minWidth: 100, },
    {
      minWidth: 150, slots: {
        header: () => <div>开票单位<br />报关单位</div>,
        default: ({ row }) => <div>
          <VText title='开票'>{row.invoice_unit}</VText>
          <VText title='报关'>{row.declare_unit}</VText>
        </div>
      }
    },
    { title: '本次入库数量', field: 'inbound_num', minWidth: 100, },
    { title: '批次入库汇总数量', field: 'total_inbound_num', minWidth: 100, },
    { title: '总入库汇总数量(累计)', field: 'add_inbound_num', minWidth: 100, },
    { title: '总入库汇总数量(总计)', field: 'sku_total_inbound_num', minWidth: 100, },
    // { title: '入库汇总数量', field: 'inbound_total_num', minWidth: 100, },
    { title: '已付款金额', field: 'payment_price', minWidth: 100, },
    {
      minWidth: 150, slots: {
        header: () => <div>应开票数量<br />已开票数量<br />待开票数量</div>,
        default: ({ row }) => <div>
          <VText title='应开票数量'>{row.all_invoice_num}</VText>
          <VText title='已开票数量'>{row.invoice_num}</VText>
          <VText title='待开票数量'>{row.wait_invoice_num}</VText>
        </div>
      }
    },
    { title: '已开票金额', field: 'invoice_price_tax', minWidth: 100, },
    {
      minWidth: 170, slots: {
        header: () => <div>入库数量（良品）<br />退货数量（良品退货）<br />不良品数量</div>,
        default: ({ row }) => <div>
          <VText title='入库数量'>{row.inbound_num}</VText>
          <VText title='退货数量'>{row.return_num}</VText>
          <VText title='不良品数量'>{row.reject_num}</VText>
        </div>
      }
    },
      {
          width: 150, slots: {
              header: () => <div>采购未税价<br />供应商税点<br />采购含税价</div>,
              default: ({ row }) => <div>
                  <VText title='采购未税价'>{row.unit_untaxed_price}</VText>
                  <VText title='供应商税点'>{row.tax_rate}</VText>
                  <VText title='采购含税价'>{row.unit_price_tax}</VText>
              </div>
          }
      },
      {
          width: 150, slots: {
              header: () => <div>采购未税报价<br />下单价</div>,
              default: ({ row }) => <div>
                  <VText title='采购未税报价'>{row.unit_price}</VText>
                  <VText title='下单价'>{row.order_price}</VText>
              </div>
          }
      },
    { title: '含税入库金额', field: 'inbound_price_tax', minWidth: 110, slots: {
      header: () => <div>含税入库金额<br />实际含税单价</div>,
      default: ({row}) => <div>
        <VText value={row.inbound_price_tax} />
        <VText value={row.billing_unit_price_tax} />
      </div>
    } },
    {
      minWidth: 150, slots: {
        header: () => <div>含税优惠（折扣）<br />含税售后<br />含税运费</div>,
        default: ({ row }) => <div>
          <VText title='含税优惠'>{row.preferential_price_tax}</VText>
          <VText title='含税售后'>{row.after_sale_price_tax}</VText>
          <VText title='含税运费'>{row.tracking_price}</VText>
        </div>
      }
    },
    { title: '实际含税入库金额', field: 'actually_inbound_price_tax', minWidth: 100, },
    {
      minWidth: 150, slots: {
        header: () => <div>开票不含税单价<br />开票不含税总额</div>,
        default: ({ row }) => <div>
          <VText title='单价'>{row.billing_unit_price}</VText>
          <VText title='总额'>{row.billing_total_price}</VText>
        </div>
      }
    },
    { title: '开票税额', field: 'billing_tax', minWidth: 100, },
    { title: '开票不含税差异率', field: 'billing_diff', minWidth: 100, },
    { title: '是否生成开票清单', field: 'is_billing_name', minWidth: 100, },
    { title: '无需生成开票清单', field: 'is_label_name', minWidth: 100, },
    { title: '生成时间', field: 'billing_time', minWidth: 170, },
    { title: '备注', field: 'remark', minWidth: 120, slots: {
      default: ({row}) => <VText value={row.remark} line={3} />
    } },
    {
      visible: !props.view, title: '操作', width: 60, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          return [<div class='nm flex flex-col gap-1'>
              <VButton auth="/purchase/finance/verification/inbound/log" link type="primary" onClick={() => handleRow('log', row)}>日志</VButton>
          </div>]
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        const data = { ...form, ...page }
        api.total(data).then(res => {
          total.value = res.data
        })
        return api.query(data)
      }
    }
  }
})
</script>
  